package com.yhh.phone.service.impl;

import com.alibaba.fastjson.JSON;
import com.yhh.common.base.ret.ApiResult;
import com.yhh.common.exception.BusinessException;
import com.yhh.common.utils.RegexUtil;
import com.yhh.phone.service.PhoneService;
import com.yhh.phone.ucpass.client.AbsRestClient;
import com.yhh.phone.ucpass.client.JsonReqClient;
import com.yhh.phone.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * 手机服务接口的实现
 */
@Slf4j
@Service // 实现类注解
@Transactional(rollbackFor = RuntimeException.class)  //事务管理,手动捕捉的异常,发生回滚
public class PhoneServiceImpl implements PhoneService {

    @Autowired
    private RedisUtil redisUtil;

    @Value("${environment}")
    private String environment;

    @Value("${yzx.sid}")
    private String sid;
    @Value("${yzx.token}")
    private String token;
    @Value("${yzx.appid}")
    private String appid;
    @Value("${yzx.reg_templateid}")
    private String regTemplateid;
    @Value("${yzx.fault_templateid}")
    private String faultTemplateid;

    @Override
    public ApiResult sendRegCode(String phoneNumber) {
        if(!RegexUtil.isMobileExact(phoneNumber)){
            throw new BusinessException("手机号格式错误");
        }
        Random random = new Random();
        Integer code = random.nextInt(8999) + 1000;


        if(!redisUtil.set(phoneNumber + "_reg_code",code,180)){
            log.error(phoneNumber + ":缓存注册码失败");
            throw new BusinessException("缓存注册码失败！");
        }
        if(environment.equalsIgnoreCase("debug")) {
            return ApiResult.success("短信发送成功");
        }
        AbsRestClient absRestClient = new JsonReqClient();
        String result = absRestClient.sendSms(sid,token,appid,regTemplateid,code.toString(),phoneNumber,null);
        log.info("短信发送结果："+result);
        if(JSON.parseObject(result).get("code").equals("000000")){
            return ApiResult.success("短信发送成功");
        }
        log.error("短信失败："+result);
        return ApiResult.error("短信发送失败");
    }

    @Override
    public ApiResult verifyRegCode(String phoneNumber, String regCode) {
        if(environment == "debug") {
            if(regCode == "1234") {
                return ApiResult.success();
            }
        }
        Object code = redisUtil.get(phoneNumber + "_reg_code");
        if(code == null){
            throw new BusinessException("注册码已失效");
        }
        if(!String.valueOf(code).equals(regCode)){
            throw new BusinessException("注册码不正确");
        }
        return ApiResult.success();

    }


}
